<template>
  <div :class="wrapperClassR" :style="wrapperStyleR" @click="onClick">
    <span :class="labelClassR" :style="labelStyleR">{{ label }}</span>
    <span :class="separatorClassR" :style="separatorStyleR">:</span>

    <span
      :class="valueClassR"
      :style="[
        valueStyleR,
        { minWidth: `${minWidth}px`, color: thresholdColor },
      ]"
    >
      <template v-if="loading">
        <i :class="skeletonClassR" :style="skeletonStyleR"></i>
      </template>
      <template v-else>
        {{ displayText }}
      </template>
    </span>

    <small v-if="tooltip">{{ tooltip }}</small>
  </div>
</template>

<script setup lang="ts">
import { defineProps, withDefaults, computed, toValue } from "vue";
import { useDataItem } from "./useDataItem";
import type { DataItemOptions, ClassType, StyleType } from "./types";

/* 默认值仅针对可选字段；必填 label / value 必须由父组件提供 */
const props = withDefaults(defineProps<DataItemOptions>(), {
  decimals: 0,
  extraDigits: 0,
  prefix: "",
  suffix: "",
  unit: "",
  formatter: (v: number) => v.toLocaleString(),
});

/* === 调用组合式函数 === */
const {
  label,
  loading,
  tooltip,
  onClick,

  displayText,
  minWidth,
  thresholdColor,

  /* 样式 / 类名（Ref<MaybeRefOrGetter<…>>） */
  wrapperClass,
  wrapperStyle,
  labelClass,
  labelStyle,
  separatorClass,
  separatorStyle,
  valueClass,
  valueStyle,
  skeletonClass,
  skeletonStyle,
} = useDataItem(props);

/* === 统一解包为真正可渲染的值 === */
function resolveClass(v: unknown): ClassType | undefined {
  return v == null ? undefined : toValue(v as any);
}
function resolveStyle(v: unknown): StyleType | undefined {
  return v == null ? undefined : toValue(v as any);
}

const wrapperClassR = computed(() => resolveClass(wrapperClass.value));
const wrapperStyleR = computed(() => resolveStyle(wrapperStyle.value));
const labelClassR = computed(() => resolveClass(labelClass.value));
const labelStyleR = computed(() => resolveStyle(labelStyle.value));
const separatorClassR = computed(() => resolveClass(separatorClass.value));
const separatorStyleR = computed(() => resolveStyle(separatorStyle.value));
const valueClassR = computed(() => resolveClass(valueClass.value));
const valueStyleR = computed(() => resolveStyle(valueStyle.value));
const skeletonClassR = computed(() => resolveClass(skeletonClass.value));
const skeletonStyleR = computed(() => resolveStyle(skeletonStyle.value));
</script>

<style scoped>
/* 按需添加默认样式 */
</style>
